<script setup lang="ts">

import {store} from "@/store/storemusic";
import {ref, onMounted, onUnmounted, computed, watch, nextTick} from "vue";
import type { PropType} from 'vue';
import ChildBoth from "@/Components/ChildBoth.vue";
import LeftList from "@/Components/LeftList.vue";
import RightUserPhoto from "@/Components/RightUserPhoto.vue";
import UndoRedoSearch from "@/Components/UndoRedoSearch.vue";
import SongBottom from "@/Components/SongBottom.vue";
import {lrcState, currentSongState} from "@/store/songStore";

// const props = defineProps({currentSong:Object, currentSongList:Array})
// const props = defineProps({
//   currentSong: Object,
//   currentSongList: {
//     type: Array as PropType<{ lrc: string; }[]>,
//     default: () => [] // 默认为空数组
//   }
// });
// let currentSong = ref(props.currentSong)
// watch(() => store.current, (newIndex) => {
//   currentSong.value = props.currentSongList[newIndex];
// }, { immediate: true });
// let songId = ref(currentSong.value?.songid)//使用可选链操作符（?.）来安全地访问这个值，这样即使value是undefined，代码也不会抛出错误

let lyricsContainerRef = ref()

const currentSongLyrics = computed(() => {
  let  lyrics = ref(currentSongState.value.songList[currentSongState.value.currentIndex]?.lrc || '')

  const lines = lyrics.value.split("[");
  let lyricArray = ref([]); // 歌词对象数组

  for (let i = 1; i < lines.length; i++) { //i=0为空
    // console.log(lines[i])
    const str = lines[i];
    const parts = str.split("]");
    const timeStr = parts[0].substring(1);
    const obj = {
      time: parseTime(timeStr),
      text: parts[1]
    };
    if(obj.text!=''){
      lyricArray.value.push(obj);
    }
  }
  // console.log(lyricArray.value)
  lrcState.value.lrcList = lyricArray.value
  console.log(lyricArray.value)
  return lyricArray.value;
});
function parseTime(timeStr) {
  const parts = timeStr.split(":");
  return +parts[0] * 60 + +parts[1]; // +一元运算符转数字
}

const itemRef = ref<any>()

// 滚动到当前歌词的函数
function scrollToCurrentLyric(index) {
  if(index>-1){
    nextTick(() => {
      const lyricsContainer = lyricsContainerRef.value;
      if (!lyricsContainer) return;
      let indexcur = lrcState.value.currentIndex
      console.log(itemRef.value[lrcState.value.currentIndex])
      const currentLyricElement = itemRef.value[lrcState.value.currentIndex];
      if (currentLyricElement) {
        // lyricsContainer.scrollTop = currentLyricElement.offsetTop - lyricsContainer.offsetHeight / 2;
        itemRef.value[lrcState.value.currentIndex].scrollIntoView({behavior:'smooth',block:'center'})

      }
    });
    console.log("正在执行滚动")
  }

}

// 监听 currentLyricIndex 变化并滚动到当前歌词
watch(()=>lrcState.value.currentIndex, (newLycIndex)=>{
  scrollToCurrentLyric(newLycIndex)
},{immediate:true});

const pageName = "SongPlayPage"

</script>

<template>
  <child-both></child-both>
  <song-bottom class="pl-30 pr-35" :pageName="pageName"></song-bottom>
  <div class="body flex">
    <left-list></left-list>
    <div class="main grow h-200 flex flex-col overflow-auto pb-15 mx-3 ">
      <undo-redo-search></undo-redo-search>

      <div class="fixed  h-100 top-35 left-80 ml-5 w-100">
        <div class="flex flex-col items-center gap-20">
          <div>
            <img class="w-80 " src="../img/唱片(合并版).png"/>
            <img class="w-50 h-50 rounded-full -mt-67 ml-14" :src="currentSongState.songList[currentSongState.currentIndex].imageUrl"/>
          </div>

          <!-- 这里底下是歌名及歌曲信息-->
          <el-scrollbar
              style="height: 150px"
              class="flex flex-col gap-3 items-center justify-center w-80 whitespace-normal text-center">
            <p class="text-4xl font-bold text-[#3b96ff]">{{ currentSongState.songList[currentSongState.currentIndex]?.title == null ? "未知" : currentSongState.songList[currentSongState.currentIndex]?.title }}</p>
            <p class="text-2xl text-bluegray">{{ currentSongState.songList[currentSongState.currentIndex]?.artist === null ? "未知" : currentSongState.songList[currentSongState.currentIndex]?.artist }}</p>
          </el-scrollbar>
        </div>
      </div>
      <!--  这里是歌词部分-->
      <el-scrollbar class="w-170 h-300 mt-15 mb-20 ml-115 " ref="lyricsContainerRef">
        <ul>
          <li v-for="(lyric, index) in currentSongLyrics"
              :key="index"
              :id="'li' + (index+1)"
              class=" lyric-line flex justify-center items-center w-160 whitespace-normal px-20 py-2 mb-2" :class="[index==lrcState.currentIndex ? 'active' : '']"
              ref="itemRef"
          >
            {{ lyric.text }}
          </li>
        </ul>

      </el-scrollbar>


    </div>
    <right-user-photo></right-user-photo>
  </div>

  <div class="fixed   w-160 h-36  pic z--1 bottom-18 left-190 opacity-23"></div>


  <!--  这里是歌曲信息部分-->

</template>

<style scoped>
.lyric-line {
  font-size: 1.5em;
  color: rgba(0, 0, 0, 0.5);
  font-family: 'Microsoft JhengHei', '微软正黑体', sans-serif;
}


.active {
  font-size: 3em;
  font-family: 'Microsoft JhengHei', '微软正黑体', sans-serif;
  @apply font-bold bg-cyan-3 rounded-full opacity-50 text-white shadow-lg shadow-cyan-500/50
}
.pic {
  /*此三个样式组合，可以保证背景图片充满整个容器. 貌似单独写在组件的style里面不生效。*/
  background-image: url(../img/child-six.png);
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}
</style>


